介紹
裝飾者模式在物件上動態加入其他行為或職責,提供除了創建子類外的另一種方法。
以下範例是利用裝飾者模式,在義大利pizza上加入大量的鳳梨。
C++範例
#include <iostream>
class Pizza
{
public:
virtual ~Pizza() {}
virtual void Make() = 0;
protected:
Pizza() {}
};
class ItalyPizza : public Pizza
{
public:
ItalyPizza() {}
~ItalyPizza() {}
void Make() override
{
std::cout << "Pizza made with italy formula" << std::endl;
}
};
class Decorator : public Pizza
{
public:
Decorator(Pizza *pizza)
{
m_Pizza = pizza;
}
virtual ~Decorator()
{
if (m_Pizza)
delete m_Pizza;
}
virtual void PutSomethingOnPizza() = 0;
protected:
Pizza *m_Pizza;
};
class EvilDecorator : public Decorator
{
public:
EvilDecorator(Pizza *pizza) : Decorator(pizza)
{
}
void Make() override
{
m_Pizza->Make();
PutSomethingOnPizza();
}
void PutSomethingOnPizza() override
{
std::cout << "Put tons of pineapple on pizza" << std::endl;
}
};
int main()
{
Pizza *italyPizza = new ItalyPizza();
Decorator *dec = new EvilDecorator(italyPizza);
dec->Make();
delete dec;
return 0;
}
Output:
Pizza made with italy formula
Put tons of pineapple on pizza